package com.lanjiu.lib.communication.work;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @description: 线程池工厂，负责重连线程调度
 * @author: Panwei
 * @date: 2019/10/28 15:21
 */
public class ExecutorServiceFactory {

    private ExecutorService mReconnectPool;  // 管理线程组，负责重连

    /**
     * 初始化boss线程池
     */
    public synchronized void initBossLoopGroup() {
        initBossLoopGroup(1);
    }

    /**
     * 初始化boss线程池
     * 重载
     *
     * @param size 线程池大小
     */
    public synchronized void initBossLoopGroup(int size) {
        destroyBossLoopGroup();
        mReconnectPool = Executors.newFixedThreadPool(size);
    }

    /**
     * 执行boss任务
     *
     * @param r
     */
    public void execBossTask(Runnable r) {
        if (mReconnectPool == null) {
            initBossLoopGroup();
        }
        mReconnectPool.execute(r);
    }

    /**
     * 释放boss线程池
     */
    public synchronized void destroyBossLoopGroup() {
        if (mReconnectPool != null) {
            try {
                mReconnectPool.shutdownNow();
            } catch (Throwable t) {
                t.printStackTrace();
            } finally {
                mReconnectPool = null;
            }
        }
    }
}
